package com.boot.web.util;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description 端口工具类
 * @date 2023/4/26 14:47
 **/

@Slf4j
public class PortUtil {

    private PortUtil() {
    }

    public static int findAvailablePort(int defaultPort) {
        int portTmp = defaultPort;
        while (portTmp < 65535) {
            if (isPortUsed(portTmp)) {
                portTmp++;
            } else {
                return portTmp;
            }
        }
        portTmp = defaultPort--;
        while (portTmp > 0) {
            if (!isPortUsed(portTmp)) {
                portTmp--;
            } else {
                return portTmp;
            }
        }
        throw new RuntimeException("no available port.");
    }

    public static boolean isPortUsed(int port) {
        boolean used = false;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
        } catch (IOException e) {
            used = true;
        }
        return used;
    }

}
